package com.crawler.waf.utils;

import java.net.URI;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;

import com.crawler.waf.support.Constants;

public class StringUtil {

	public static String getHost() {
		try {
			URI uri = URI.create("");
			uri.getRawPath();
			return uri.getHost();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

    public static String getURI(String host, Integer port, String url) {
        if (host == "") {
            return "";
        }
        
        int index = url.indexOf(host);
        if (index == -1) {
            return "";
        }
        
        url =  url.substring(index+host.length());
        String portKey = ":" + port;
        if(url.startsWith(portKey)){
        	url = url.substring(portKey.length());
        }
        return url;
    }
    
    /**
     * 处理代理请求url
     * @param request
     * @return
     */
    public static String urlHandler(HttpServletRequest request) {
		StringBuffer requestURL = request.getRequestURL();
		String reqString = requestURL.toString();
		String queryStr = request.getQueryString();
		// 判断请求参数是否为空
		if (!StringUtils.isEmpty(queryStr)) {
			if (queryStr.indexOf("&")>-1) {
				String [] paramString = queryStr.split("&");
				requestURL.append("?");// 参数
				for (String string : paramString) {
					if (string.indexOf(Constants.PROXY_PARAM)>-1) {
						continue;
					}
					requestURL.append(string).append("&");// 参数
				}
				if (requestURL.lastIndexOf("&")>-1) {
					reqString = requestURL.substring(0, requestURL.length()-1).toString();
				}
			}else {
				if (queryStr.indexOf(Constants.PROXY_PARAM)==-1) {
					reqString = requestURL.append("?").append(queryStr).toString();// 参数
				}
			}
		}
		return reqString;
	}
}
